<style lang="less">
@import "./../common.less";
</style>
<template>
  <div>
    <!-- 搜索添加栏 -->
    <Row>
      <Card>
        <div style="margin-top: 6px">
          <Form ref="searchData" :model="searchData" :rules="searchReg" :label-width="80">
            <Row>
              <i-col :xs="24" :md="12" :lg="6">
                <FormItem label="指标等级" prop="indexType">
                  <Select v-model="searchData.indexType" placeholder="请选择指标等级" style="width:185px">
                    <Option value="一级指标">一级指标</Option>
                    <Option value="二级指标">二级指标</Option>
                  </Select>
                </FormItem>
              </i-col>
              <i-col :xs="24" :md="12" :lg="6">
                <FormItem label="指标名称">
                  <Input
                    search
                    placeholder="请输入指标名称"
                    v-model="searchData.indexName"
                    style="width: auto"
                  >
                    <Icon type="ios-search" slot="suffix" />
                  </Input>
                </FormItem>
              </i-col>
              <i-col :xs="24" :md="12" :lg="6" v-show="searchData.indexType==='二级指标'">
                <FormItem label="牵头单位">
                  <Input
                    search
                    placeholder="请输入牵头单位"
                    v-model="searchData.leadUnitName"
                    style="width:150px"
                  >
                    <Icon type="ios-search" slot="suffix" />
                  </Input>
                </FormItem>
              </i-col>
              <i-col :xs="24" :md="12" :lg="6" v-show="searchData.indexType==='二级指标'">
                <FormItem label="责任单位">
                  <Input
                    search
                    placeholder="请输入搜索内容"
                    v-model="searchData.respUnitName"
                    style="width: 150px"
                  >
                    <Icon type="ios-search" slot="suffix" />
                  </Input>
                </FormItem>
              </i-col>
            </Row>
            <Row>
              <i-col :xs="24" :md="12" :lg="6">
                <FormItem label="指标年份">
                  <Col span="12">
                    <DatePicker
                      type="year"
                      format="yyyy"
                      v-model="searchData.dateTime"
                      @on-change="handlerFormat"
                      placeholder="请选择指标年份"
                      style="width:185px"
                    ></DatePicker>
                  </Col>
                </FormItem>
              </i-col>
            </Row>
            <FormItem>
              <Button type="primary" @click="seachSubmit('searchData')">提交搜索</Button>
              <Button @click="seachReset('searchData')" style="margin-left: 8px">重置搜索</Button>
            </FormItem>
          </Form>
        </div>
      </Card>
    </Row>
    <!-- 导入并校验 -->
    <div v-if="isSpuerAdmins.add" style="margin-top:10px;">
      <!--
          本地  action="api/countryIndicators/uploadCityIndex"
          线上  action="/countryIndicators/uploadCityIndex"
      -->
      <Card title="导入EXCEL">
        <Upload
          ref="upload"
          :before-upload="handleUpload2"
          :on-success="handleSuccess2"
          :format="['xls','xlsx']"
          :on-format-error="handleFormatError2"
          :action="importUrl"
        >
          <Button type="success" @click="downloadTemplate" style="margin-right: 20px;">下载市对县指标模板</Button>
          <Tooltip content="温馨提示：上传文件前请先下载模板，依照模板格式上传" placement="top-start" max-width="220">
            <Button type="primary" icon="ios-cloud-upload-outline" @click="exports">导入市对县指标</Button>
          </Tooltip>
        </Upload>

        <div v-if="file !== null">
          文件名: {{ file.name }}
          <Button type="primary" @click="upload" :disabled="isBanUpload">点击上传</Button>
          <h3 style="color:#ff6600;">{{warnTips}}</h3>
          <div style="margin:10px 0;">
            导入批次号：{{batchNum}}
            <DatePicker
              type="year"
              format="yyyy"
              v-model="indexsTime"
              @on-change="changeIndexTime"
              placeholder="请选择指标年份(必填)"
              style="width: auto;margin:0 10px;"
            ></DatePicker>
            <Tooltip
              content="温馨提示：确认上传前请确认已经选择了指标年份 和 重新校验所上传的数据！！"
              max-width="250"
              placement="top-start"
            >
              <Button type="success" @click="clickExport" :disabled="!isBanUpload">确认导入</Button>
            </Tooltip>
          </div>
        </div>
        <!-- 校验表格回显 -->
        <Table
          v-if="isShowCheckTable"
          border
          :height="450"
          :columns="checkHead"
          :data="checkData"
          :row-class-name="rowClassName"
          :loading="checkTableLoading"
        ></Table>
      </Card>
    </div>
    <!-- 以上为导入并校验 -->
    <!-- 表格-->
    <Row style="margin-top:20px">
      <Card>
        <div class="btn-arrs">
          <Button v-if="isSpuerAdmins.add" type="info" @click="addTarget($event)">添加永泰市对县指标</Button>
        </div>
        <div>
          <Table
            :loading="TableOneLoading"
            border
            :columns="colIndexOne"
            :data="indexOne"
            v-if="isIndexOne"
          ></Table>
          <Table
            :loading="TableTwoLoading"
            border
            :columns="colIndexTwo"
            :data="indexTwo"
            v-if="isIndexTwo"
          ></Table>
          <Table
            :loading="TableThreeLoading"
            border
            :columns="columns7"
            :data="data6"
            v-if="searchData.indexType==='三级指标'"
          ></Table>
        </div>
        <div style="margin:20px 0;margin-left:35%;">
          <Page
            @on-change="pageNumberChange"
            :current="pageCurrent"
            :page-size="pageSize"
            :total="pageTotal"
            @on-page-size-change="pageSizeChange"
            show-elevator
            show-sizer
          />
        </div>
      </Card>
    </Row>

    <!-- 模态框  增加指标-->
    <Modal v-model="addIndex" :title="targetName" @on-cancel="closeAddIndex" width="700px">
      <Form ref="formCityList" :model="formCityList" :rules="ruleValidate" :label-width="100">
        <FormItem label="指标名称" prop="indexName">
          <Input v-model="formCityList.indexName" placeholder="请输入指标名称" style="width:500px"></Input>
        </FormItem>
        <FormItem label="指标等级" prop="indexType">
          <Select
            v-model="formCityList.indexType"
            placeholder="请选择指标等级"
            style="width:500px"
            :disabled="isIndexType"
          >
            <Option value="一级指标">一级指标</Option>
            <Option value="二级指标">二级指标</Option>
          </Select>
        </FormItem>
        <FormItem label="上级指标" prop="superiorIndexId" v-if="isFormFlase">
          <Select v-model="formCityList.superiorIndexId" placeholder="请选择上级指标" style="width:500px">
            <Option v-for="item in lastIndex" :value="item.id+''" :key="item.id">{{ item.indexName}}</Option>
          </Select>
        </FormItem>
        <FormItem label="匹配单位" prop="leadUnit" v-if="isFormFlase">
          <Select
            filterable
            clearable
            placeholder="请选择匹配单位"
            v-model="formCityList.leadUnit"
            style="width:500px"
          >
            <Option
              v-for="item in getDepartmentList"
              :value="item.departcode"
              :key="item.departcode"
            >{{ item.department }}</Option>
          </Select>
        </FormItem>
        <FormItem label="牵头单位" prop="leadUnitName" v-if="isFormFlase">
          <Input placeholder="请输入牵头单位" v-model="formCityList.leadUnitName" style="width:500px"></Input>
        </FormItem>
        <FormItem label="责任单位" prop="respUnitName" v-if="isFormFlase">
          <Input placeholder="请选择责任单位" v-model="formCityList.respUnitName" style="width:500px"></Input>
        </FormItem>
        <FormItem label="部门" prop="branchs" v-if="isFormFlase">
          <Select
            filterable
            clearable
            placeholder="请选择部门"
            v-model="formCityList.branchs"
            style="width:500px"
            @on-change="changBranch"
          >
            <Option
              v-for="item in branchList"
              :value="item.departAddr"
              :key="item.departAddr"
            >{{ item.departAddr }}</Option>
          </Select>
        </FormItem>
        <FormItem label="分管县领导" prop="leadNames" v-if="isFormFlase">
          <Select
            filterable
            clearable
            multiple
            placeholder="请选择分管县领导"
            v-model="formCityList.leadNames"
            style="width:500px"
          >
            <Option
              v-for="item in leaderList"
              :value="item.id+''"
              :key="item.id"
            >{{ item.nickName }}</Option>
          </Select>
        </FormItem>
        <FormItem label="标准值" prop="standard" v-if="isFormFlase">
          <Input v-model="formCityList.standardValue" placeholder="请输入标准值" style="width:500px"></Input>
        </FormItem>
        <FormItem label="权数" prop="weight" v-if="isFormFlase">
          <Input v-model="formCityList.weight" placeholder="请输入0 ~ 100 整数" style="width:500px"></Input>
        </FormItem>
        <FormItem label="指标年份" prop="dateTime">
          <DatePicker
            type="year"
            format="yyyy"
            :value="formCityList.dateTime"
            @on-change="IndexFormat"
            placeholder="请选择指标年份"
            style="width:185px"
          ></DatePicker>
        </FormItem>
      </Form>
      <div slot="footer">
        <Button
          v-if="isSpuerAdmins.add"
          type="primary"
          :loading="submitloading"
          style="width:120px"
          @click="BtnSubmit($event)"
        >
          <span v-if="!submitloading">提交</span>
          <span v-else>提交中...</span>
        </Button>
        <Button @click="closeAddIndex">取消</Button>
      </div>
    </Modal>

    <!-- 导入检验模态框 -->
    <Modal v-model="checkModal" title="编辑" width="700px;" @on-cancel="closeCheckModal">
      <Form ref="checkForm" :model="checkForm" :label-width="80">
        <FormItem label="牵头单位">
          <Input disabled v-model="checkForm.name23"></Input>
        </FormItem>
        <FormItem label="匹配单位">
          <Select filterable clearable v-model="checkForm.cell23">
            <Option
              v-for="item in getDepartmentList"
              :value="item.departcode"
              :key="item.departcode"
            >{{ item.department }}</Option>
          </Select>
        </FormItem>
        <FormItem label="数据采集配合单位">
          <Input disabled v-model="checkForm.name24"></Input>
        </FormItem>
        <FormItem label="一级指标">
          <Input disabled v-model="checkForm.cell4" placeholder="请输入一级指标"></Input>
        </FormItem>
        <FormItem label="二级指标">
          <Input disabled v-model="checkForm.cell0" placeholder="请输入二级指标"></Input>
        </FormItem>
        <FormItem label="权重">
          <InputNumber disabled v-model="checkForm.cell1" placeholder="请输入权重"></InputNumber>
        </FormItem>
        <FormItem label="备注">
          <Input disabled v-model="checkForm.remark" type="textarea" placeholder="请输入备注" />
        </FormItem>
        <FormItem label="标准值">
          <Input disabled v-model="checkForm.cell5" placeholder="请输入标准值" />
        </FormItem>
        <FormItem label="请选择方向">
          <Input disabled v-model="checkForm.cell6" placeholder="请选择方向" />
        </FormItem>
      </Form>
      <div slot="footer">
        <Button
          type="primary"
          style="width:120px"
          @click="handleSave"
          :loading="loadingStatus"
        >{{loadingStatus ? "提交中..." : "提交"}}</Button>
        <Button @click="closeCheckModal">取消</Button>
      </div>
    </Modal>
  </div>
</template>
<script>
import excel from "@/libs/excel";
import { cityAjax, checkAjax } from "@/api/city";
import { URL } from "@/libs/util";
const regNumber = new RegExp("^(?:0|[1-9][0-9]?|100)$");
// 以防命名冲突
const HOST = URL;
// 查询校验
const QUERYCHECK_URL = "/townIndicators/queryImport";
// 修改保存
const UPDEXCEL_URL = "/townIndicators/updateExcelData";
// 确认导入接口
const CONFIRM_URL = "/countryIndicators/saveExcelData";
export default {
  data() {
    const validateWeight = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请填写分数"));
      } else if (!regNumber.test(value)) {
        callback(new Error("请输入0 ~ 100 正整数！"));
      } else {
        callback();
      }
    };
    return {
      // 是否为超级管理员
      isSpuerAdmins: {
        add: true,
        action: "inline-block"
      },
      // 导入市对县指标路径
      importUrl: URL + "/countryIndicators/uploadCityIndex",
      departmentList: [], // 部门列表
      addIndex: false, // 显示增加模态框
      isIndexOne: false, // 是否指标等级一
      isIndexTwo: true, // 是否指标等级二
      submitloading: false, // 增加模态框loading
      TableOneLoading: true, // 表格loading 一级指标
      checkTableLoading: true, // 校验表格loading
      TableTwoLoading: true, // 表格loading 二级指标
      isFormFlase: false, // form表单显示
      isFormTrue: true, // 一级指标显示Input
      isFormWeight: false, // 二级指标显示Input
      targetName: "", // 增加或者编辑的Title
      pageTotal: 0, // 总页数
      pageSize: 10, // 条数
      pageNumber: 1, // 页码
      pageCurrent: 1, // 当前页
      indexOne: [], // 一级指标数据
      indexTwo: [], // 二级指标数据
      storeSuperiorIndexId: "", // 处理当指标Id与select选择指标的Value不一致
      // superiorIndexSelect: [], // form选择指标
      isIndexType: false,
      excelUpdate: "",
      searchData: {
        // 搜索数据
        indexType: "二级指标",
        responsibilityUnit: "",
        leadUnit: "",
        leadUnitName: "",
        respUnitName: "",
        indexName: "",
        dateTime: ""
      },
      colIndexOne: [
        // 一级指标 表格表头
        {
          title: "序号",
          type: "index",
          width: 80,
          align: "center"
        },
        {
          title: "指标等级",
          key: "indexType"
        },
        {
          title: "指标名称",
          key: "indexName"
        },
        {
          title: "权数值",
          key: "weight",
          width: 80
        },
        {
          title: "操作",
          key: "action",
          width: 200,
          align: "center",
          render: (h, params) => {
            return h("div", [
              h(
                "Button",
                {
                  props: {
                    type: "primary",
                    size: "small"
                  },
                  style: {
                    marginRight: "20px"
                  },
                  on: {
                    click: () => {
                      // 显示模态框
                      if (params.row.id !== "") {
                        var row = params.row;
                        this.formCityList = Object.assign(row, {
                          year: params.row.dateTime
                        });
                        this.formCityList = JSON.parse(
                          JSON.stringify(this.formCityList)
                        );
                      } else {
                        this.$Message.error("刷新页面后尝试此操作");
                        return;
                      }
                      this.isIndexType = true; // 更新改修指标，禁止修改指标等级
                      this.addIndex = true;
                      this.isFormFlase = false;
                      this.isFormTrue = true;
                      this.targetName = "编辑指标";
                    }
                  }
                },
                "查看或编辑"
              ),
              h(
                "Button",
                {
                  props: {
                    type: "error",
                    size: "small"
                  },
                  style: {
                    display: this.isSpuerAdmins.action
                  },
                  on: {
                    click: () => {
                      this.remove(params);
                    }
                  }
                },
                "删除"
              )
            ]);
          }
        }
      ],
      colIndexTwo: [
        // 二级指标 表格表头
        {
          title: "指标等级",
          key: "indexType",
          width: 100
        },
        {
          title: "指标名称",
          key: "indexName"
        },
        {
          title: "牵头单位",
          key: "leadUnitName"
        },
        {
          title: "责任单位",
          key: "respUnitName"
        },
        {
          title: "分管县领导",
          key: "leadNames",
          render: (h, params) => {
            let text = "";
            let list = params.row.leadNames;
            let branch = this.branchList;
            // 循环回显表格分管领导字段
            for (let i = 0; i < branch.length; i++) {
              for (let j = 0; j < branch[i].userlists.length; j++) {
                let item = branch[i].userlists;
                for (let p = 0; p < list.length; p++) {
                  if (list[p] + "" === item[j].id + "") {
                    text += item[j].nickName + ",";
                  }
                }
              }
            }
            return h("div", {}, text);
          }
        },
        {
          title: "权数",
          key: "weight",
          width: 80
        },
        {
          title: "操作",
          key: "action",
          width: 180,
          align: "center",
          render: (h, params) => {
            return h("div", [
              h(
                "Button",
                {
                  props: {
                    type: "primary",
                    size: "small"
                  },
                  style: {
                    marginRight: "5px"
                  },
                  on: {
                    click: () => {
                      this.formCityList = JSON.parse(
                        JSON.stringify(params.row)
                      );
                      console.log(this.formCityList);
                      // 赋值弹窗部门值
                      let arr = this.formCityList.leadNames;
                      let branch = this.branchList;
                      if (arr === []) {
                        console.log(this.leaderList);
                        this.leaderList = data[0].userlists; // 领导数组
                      } else {
                        for (let i = 0; i < branch.length; i++) {
                          for (let j = 0; j < branch[i].userlists.length; j++) {
                            let item = branch[i].userlists;
                            if (Number(arr[0]) === item[j].id) {
                              console.log(item[j]);
                              this.leaderList = item;
                              this.formCityList.leadNames =
                                params.row.leadNames;
                              this.formCityList.branchs = branch[i].departAddr;
                            }
                          }
                        }
                      }

                      this.isIndexType = true; // 更新改修指标，禁止修改指标等级
                      this.addIndex = true;
                      this.isFormfalse = true;
                      this.isFormTrue = false;
                      this.targetName = "编辑指标";
                    }
                  }
                },
                "查看或编辑"
              ),
              h(
                "Button",
                {
                  props: {
                    type: "error",
                    size: "small"
                  },
                  style: {
                    display: this.isSpuerAdmins.action
                  },
                  on: {
                    click: () => {
                      this.remove(params);
                    }
                  }
                },
                "删除"
              )
            ]);
          }
        }
      ],
      // 验证添加或者编辑表单
      ruleValidate: {
        superiorIndexId: [
          {
            required: true,
            message: "请选择上级指标",
            trigger: "change"
          }
        ],
        indexName: [
          {
            required: true,
            message: "请输入指标名称",
            trigger: "blur"
          }
        ],
        indexType: [
          {
            required: true,
            message: "请选择指标等级",
            trigger: "change"
          }
        ],
        weight: [
          {
            required: true,
            validator: validateWeight,
            trigger: "blur"
          }
        ],
        leadUnit: [
          {
            required: true,
            message: "请选择匹配单位",
            trigger: "change"
          }
        ],
        leadUnitName: [
          {
            required: true,
            message: "请输入牵头单位",
            trigger: "blur"
          }
        ],
        respUnitName: [
          {
            required: true,
            message: "请输入责任单位",
            trigger: "blur"
          }
        ],
        dateTime: [
          {
            required: true,
            type: "string",
            message: "请选择年份",
            trigger: "change"
          }
        ]
      },
      // 验证搜索
      searchReg: {
        indexType: [
          {
            required: true,
            message: "请选择指标等级",
            trigger: "change"
          }
        ]
      },
      // 表单
      formCityList: {
        id: "",
        indexName: "", // 指标名称
        indexType: "二级指标", // 指标类型
        superiorIndexId: "", // 上级单位 一级指标没有上级单位
        mainUnit: "", // 主要牵头单位 用来填写分数和审核分数
        leadUnitName: "", // 牵头单位
        respUnitName: "", // 责任单位
        leadUnit: "", // 匹配单位
        branchs: "", // 部门
        leadNames: [], // 分管县领导 多选
        score: "", // 分数
        standardValue: "", // 标准值
        direction: "", // 方向
        weight: "", // 权数
        dateTime: "", // 年份时间
        year: "" // 年份
      },
      leaderList: [],
      branchList: [],
      // 上传表格
      uploadLoading: false,
      progressPercent: 0,
      showProgress: false,
      showRemoveFile: false,
      file: null,
      tableData: [], // 上传Excel 内容
      tableTitle: [], //
      excelTime: "",
      tableLoading: false,
      UploadLoadingBtn: false,
      /** ************************************** */
      // 导入的回显表
      indexsTime: "",
      batchNum: "", // 导入批次
      checkHead: [
        {
          title: "序号",
          type: "index",
          width: 60,
          align: "center"
        },
        {
          title: "一级指标",
          key: "cell4",
          width: 200
        },
        {
          title: "二级指标",
          key: "cell0",
          width: 200
        },
        {
          title: "权重",
          key: "cell1",
          width: 70
        },
        {
          title: "牵头单位",
          key: "name23",
          width: 250
        },
        {
          title: "备注",
          key: "remark",
          width: 200
        },
        {
          title: "数据采集配合单位",
          key: "name24",
          width: 250
        },
        {
          title: "标准值",
          key: "cell5",
          width: 200
        },
        {
          title: "方向",
          key: "cell6",
          width: 60
        },
        {
          title: "操作",
          key: "action",
          width: 100,
          fixed: "right",
          render: (h, params) => {
            return h("div", [
              h(
                "Button",
                {
                  props: {
                    type: "primary",
                    size: "large"
                  },
                  on: {
                    click: () => {
                      this.checkForm = JSON.parse(JSON.stringify(params.row));
                      this.checkForm.cell1 = parseInt(this.checkForm.cell1);
                      this.checkModal = true;
                    }
                  }
                },
                "编辑"
              )
            ]);
          }
        }
      ],
      checkData: [],
      isBanUpload: false,
      isShowCheckTable: false,
      warnTips: "", // 警告提示
      // 校验模态框
      checkModal: false,
      checkForm: {
        name23: "", // 牵头单位
        cell4: "", // 一级指标
        cell0: "", // 二级指标
        cell1: 100, // 权重
        cell23: "", // 匹配单位
        cell24: "", // 数据采集配合单位
        remark: "", // 备注
        cell5: "", // 标准值
        cell6: "" // 方向
      },
      loadingStatus: false,
      lastIndex: [] // 上级指标
    };
  },
  methods: {
    // FORM表单年份
    IndexFormat(year) {
      this.formCityList.dateTime = year;
    },
    // 搜索框年份
    handlerFormat(year) {
      this.searchData.dateTime = year;
    },
    // 关闭模态框增加或者编辑
    closeAddIndex() {
      // this.indexTwo = Object.assign({}, this.indexTwo);
      this.addIndex = false;
      this.isIndexType = false;
      this.isFormFlase = false;
    },
    // 添加指标 编辑指标
    BtnSubmit(e) {
      this.$refs["formCityList"].validate(valid => {
        if (valid) {
          this.submitloading = true;
          if (this.targetName === "永泰市对县指标增加") {
            this._addIndexCity(this.formCityList)
              .then(res => {
                if (res.code === "200") {
                  this.$Message.success("成功");
                  this.submitloading = false;
                  // 按照填入的indexType刷新页面
                  if (this.formCityList.indexType === "一级指标") {
                    let indexType = {
                      indexType: this.formCityList.indexType,
                      pageSize: this.pageSize
                    };
                    this._getCityList(indexType, this.pageSize, this.page).then(
                      res => {
                        // this.superiorIndexSelect = [];
                        // res.results.firstIndex.forEach(item => {
                        //   this.superiorIndexSelect.push(item.indexName);
                        // });
                        this.indexOne = res.results.list;
                        this.addIndex = false;
                        this.lastIndex = res.results.firstIndex;
                      }
                    );
                  } else if (this.formCityList.indexType === "二级指标") {
                    let indexType = {
                      indexType: this.formCityList.indexType
                    };
                    this._getCityList(indexType, this.pageSize, this.page).then(
                      res => {
                        this.indexTwo = res.results.list;
                        this.addIndex = false;
                        this.isIndexOne = false;
                        this.isIndexTwo = true;
                        this.TableTwoLoading = false;
                      }
                    );
                  }
                  this.addIndex = false;
                }
              })
              .catch(err => {
                console.log(err);
              });
          } else if (this.targetName === "编辑指标") {
            this._updateIndexCity(this.formCityList).then(res => {
              if (res.code === "200") {
                this.submitloading = false;
                this.addIndex = false;
                this.$Message.success("修改成功");
                if (this.formCityList.indexType === "一级指标") {
                  let indexType = {
                    indexType: this.formCityList.indexType
                  };
                  this._getCityList(
                    indexType,
                    this.pageSize,
                    this.pageNumber
                  ).then(res => {
                    this.indexOne = res.results.list;
                    this.addIndex = false;
                  });
                } else if (this.formCityList.indexType === "二级指标") {
                  let indexType = {
                    indexType: this.formCityList.indexType
                  };

                  this._getCityList(
                    indexType,
                    this.pageSize,
                    this.pageNumber
                  ).then(res => {
                    this.indexTwo = res.results.list;
                    this.addIndex = false;
                    this.isIndexOne = false;
                    this.isIndexTwo = true;
                    this.TableTwoLoading = false;
                  });
                }
              }
            });
          }
        } else {
          this.$Message.error("带*为必填项");
        }
      });
    },
    // 删除指标
    remove(params) {
      this.pageCurrent = this.pageNumber;
      this.$Modal.confirm({
        title: "删除指标",
        content: "<p>删除后将无法恢复</p>",
        onOk: () => {
          this._removeIndexCity({ id: params.row.id }).then(res => {
            if (res.code === "200") {
              this.$Message.success("删除成功");
              this.seachSubmit("searchData", "remove");
            } else {
              this.$Message.error("操作失败");
            }
          });
        },
        onCancel: () => {
          this.$Message.info("已取消");
        }
      });
    },
    // 打开模态框
    addTarget(e) {
      this.targetName = "永泰市对县指标增加";
      // 清除INPUT框
      this.resetInput();
      this.isFormFlase = false;
      this.isFormTrue = true;
      this.addIndex = true;
      this.isIndexType = false;
    },
    // 搜索查询
    seachSubmit(name, isRemove) {
      this.$refs[name].validate(valid => {
        if (valid) {
          this.TableOneLoading = true;
          this.TableTwoLoading = true;
          // 清除formCityList表单
          this.resetInput();
          if (isRemove) {
            this.pageNumber = this.pageCurrent;
          } else {
            this.pageTotal = 0;
            this.pageSize = 10;
            this.pageNumber = 1;
          }
          const formData = Object.assign(this.formCityList, this.searchData);
          this._getCityList(formData, this.pageSize, this.pageNumber).then(
            res => {
              if (res.code === "200") {
                // 按照IndexType类别 填入不同Tabel里
                if (this.searchData.indexType === "一级指标") {
                  this.$Message.success("查询成功");
                  this.indexOne = res.results.list;
                  // this.pageTotal = parseInt(res.results.pageTotal) * 10;
                  this.TableOneLoading = false;
                  this.isIndexOne = true;
                  this.isIndexTwo = false;
                } else if (this.searchData.indexType === "二级指标") {
                  this.isIndexOne = false;
                  this.TableTwoLoading = false;
                  this.isIndexTwo = true;
                  this.$Message.success("查询成功");
                  this.indexTwo = res.results.list;
                  // this.pageTotal = parseInt(res.results.pageTotal) * 10;
                }
              } else {
                this.$Message.error("查询失败");
              }
            }
          );
        } else {
          this.$Message.error("带*不可为空");
        }
      });
    },
    // 重置搜索
    seachReset(name) {
      this.searchData = {
        indexType: "二级指标",
        ducyUnit: "",
        lead: "",
        indexName: ""
      };
    },
    // 重置表单
    resetInput() {
      if (this.formCityList.indexType !== "") {
        this.$refs["formCityList"].resetFields();
        this.formCityList = {
          indexName: "",
          indexType: "",
          superiorIndexId: "",
          leadUnit: "",
          responsibilityUnit: "",
          score: "",
          standardValue: "",
          direction: "",
          weight: "",
          dateTime: "",
          mainUnit: ""
        };
      }
    },
    // 页码
    pageNumberChange(number) {
      this.pageNumber = number;
      this._getCityList(this.searchData, this.pageSize, this.pageNumber).then(
        res => {
          if (res.code === "200") {
            // 按照IndexType类别 填入不同Tabel里
            if (
              this.formCityList.indexType === "一级指标" ||
              this.searchData.indexType === "一级指标"
            ) {
              this.indexOne = res.results.list;
              this.$Message.success("查询成功");
            } else if (
              this.formCityList.indexType === "二级指标" ||
              this.searchData.indexType === "二级指标"
            ) {
              this.indexTwo = res.results.list;
              this.$Message.success("查询成功");
            }
          } else {
            this.$Message.error("查询失败");
          }
        }
      );
    },
    // 页数
    pageSizeChange(pageSize) {
      this.pageSize = pageSize;
      this._getCityList(this.searchData, this.pageSize, this.pageNumber).then(
        res => {
          if (res.code === "200") {
            // 按照IndexType类别 填入不同Tabel里
            if (this.formCityList.indexType === "一级指标") {
              this.indexOne = res.results.list;
            } else if (this.formCityList.indexType === "二级指标") {
              this.indexTwo = res.results.list;
              this.$Message.success("查询成功");
            }
          } else {
            this.$Message.error("查询失败");
          }
        }
      );
    },
    // 获取数据
    _getCityList(form, pageSize, pageNumber) {
      const url = "/countryIndicators/query";
      const key = "countryIndicatorsFilter";
      let formData = Object.assign(form, {
        pageSize: pageSize,
        pageNumber: pageNumber
      });
      return new Promise((resolve, reject) => {
        cityAjax({ formData, url, key }).then(res => {
          if (res.data !== undefined) {
            resolve(res.data);
          } else {
            reject();
          }
        });
      });
    },
    // 添加指标
    _addIndexCity(formData) {
      const url = "/countryIndicators/insert";
      const key = "countryIndicatorsEntity";
      return new Promise((resolve, reject) => {
        cityAjax({ formData, url, key }).then(res => {
          if (res.data !== undefined) {
            resolve(res.data);
          } else {
            reject();
          }
        });
      });
    },
    // 修改指标
    _updateIndexCity(formData) {
      const url = "/countryIndicators/update";
      const key = "countryIndicatorsEntity";
      return new Promise((resolve, reject) => {
        cityAjax({ formData, url, key }).then(res => {
          if (res.data !== undefined) {
            resolve(res.data);
          } else {
            reject();
          }
        });
      });
    },
    // 删除
    _removeIndexCity(formData) {
      const url = "/countryIndicators/delete";
      const key = "countryIndicatorsEntity";
      return new Promise((resolve, reject) => {
        cityAjax({ formData, url, key }).then(res => {
          if (res.data !== undefined) {
            resolve(res.data);
          } else {
            reject();
          }
        });
      });
    },
    /**
     * 下载市对县指标上传模板
     */
    downloadTemplate() {
      window.open(
        HOST +
          "/townScore/downTownScoreMoudle?fileName=cityIndexMould.xls&chinaName=市对县指标上传模板.xls"
      );
    },
    /** 查询校验表格 **************************** ******************/
    _queryCheckAjax(form, url, pageNumber, pageSize) {
      // const url = "/townIndicators/queryImport";
      const keyOne = "excelDTO";
      let formData = Object.assign(form, {
        pageSize: pageSize,
        pageNumber: pageNumber
      });
      return new Promise((resolve, reject) => {
        checkAjax({ formData, url, keyOne }).then(res => {
          if (res.data.code === "200") {
            resolve(res.data);
          } else {
            reject(error);
          }
        });
      });
    },
    changeIndexTime(year) {
      this.indexsTime = year;
    },
    // 导入excel
    // 阻止自动上传文件
    handleUpload2(file) {
      this.file = file;
      return false;
    },
    // 上传文件
    handleSuccess2(res, file) {
      if (res.code === "200") {
        this.batchNum = res.results.batchNum;
        this.$Notice.success({
          title: res.message
        });
        let formData = {
          batchNum: this.batchNum
        };
        // 回显校验表格
        this.checkTableLoading = true;
        const keyOne = "excelDTO";
        this._queryCheckAjax(formData, QUERYCHECK_URL).then(ressult => {
          if (ressult.code === "200") {
            this.checkData = ressult.results.list;
            this.isBanUpload = true;
            this.checkTableLoading = false;
            this.$Message.success(ressult.message);
            this.warnTips = ressult.results.warn;
          } else {
            this.$Message.error(ressult.message);
          }
        });
      } else if (res.code === "500") {
        this.$Notice.error({
          title: res.message
        });
      }
    },
    // 点击上传文件
    upload() {
      this.$refs.upload.post(this.file); // 请求
      this.isShowCheckTable = true;
    },
    // 验证上传格式
    handleFormatError2(file) {
      this.$Notice.warning({
        title: "文件格式错误",
        desc: "文件" + file.name + " 格式错误, 请选择xls或者xlsx"
      });
    },
    // 最终确认认导入
    clickExport() {
      if (this.indexsTime !== "") {
        this.$Modal.confirm({
          width: 600,
          title: "是否确认导入",
          content:
            "<p>如有橙黄警告信息数据，该条数据将不会被保存，是否确认导入？</p>" +
            "<p>" +
            this.warnTips +
            "</p>",
          onOk: () => {
            this.confirmImport();
          },
          onCancel: () => {}
        });
      } else {
        this.$Message.error("请选择导入指标年份");
      }
    },
    // 确认导入
    confirmImport() {
      if (this.indexsTime !== "") {
        let formData = {
          batchNum: this.batchNum,
          dateTime: this.indexsTime,
          cell23: this.cell23,
          cell24: this.cell24
        };
        this._queryCheckAjax(formData, CONFIRM_URL).then(res => {
          if (res.code === "200") {
            this.$Message.success(res.message);
            // 重新查询表格
            let indexType = {
              indexType: "二级指标"
            };

            this._getCityList(indexType, this.pageSize, this.pageNumber).then(
              res => {
                this.indexTwo = res.results.list;
                this.addIndex = false;
                this.isIndexOne = false;
                this.isIndexTwo = true;
                this.TableTwoLoading = false;
              }
            );
          } else {
            this.$Message.error(res.message);
          }
          this.isShowCheckTable = false;
          // 清除数据
          setTimeout(() => {
            this.isBanUpload = false;
            this.indexsTime = "";
            this.warnTips = "";
            this.file = null;
          }, 500);
        });
      } else {
        this.$Message.error("请先选择指标年份");
      }
    },
    // 修改保存
    handleSave(index) {
      this.loadingStatus = true;
      let formData = this.checkForm;
      this._queryCheckAjax(formData, UPDEXCEL_URL).then(res => {
        this.checkTableLoading = true;
        this.checkModal = false;
        if (res.code === "200") {
          this.checkData = res.results.list;
          this.checkTableLoading = false;
          this.loadingStatus = false;
          this.$Message.success(res.message);
          this.warnTips = res.results.warn;
        } else {
          this.$Message.error(res.message);
        }
      });
    },
    selectTestType(val) {
      let arr = this.$store.state.user.departmentList; // 获取单位数组
      for (let i = 0; i < arr.length; i++) {
        if (val === arr[i].departcode) {
          return arr[i].department;
        }
      }
    },
    /**
     * 校验表格时判断是否有误显示红色
     * @param {row} 表格行数据
     */
    rowClassName(row, index) {
      if (row.avail === 0) {
        return "demo-table-error-row";
      }
      return "";
    },
    exports() {
      this.isBanUpload = false;
    },
    closeCheckModal() {
      this.checkModal = false;
    },
    // 获取分管县领导和部门
    _getleadersList(form) {
      const url = "/app/sys/getManage";
      let formData = {};
      return new Promise((resolve, reject) => {
        cityAjax({ formData, url }).then(res => {
          if (res.data !== undefined) {
            resolve(res.data);
          } else {
            reject();
          }
        });
      });
    },
    // 改变部门时获取数据
    changBranch() {
      let branch = this.formCityList.branchs;
      this.branchList.forEach(item => {
        if (item.departAddr === branch) {
          console.log(item.userlists);
          this.leaderList = item.userlists;
        }
      });
      this.formCityList.leadNames = []; // 切换部门时清空领导列表
    }
  },
  watch: {
    // form表单根据指标等级
    formCityList: {
      handler(newVal) {
        if (newVal.indexType !== undefined) {
          if (newVal.indexType === "一级指标") {
            this.isFormFlase = false;
            this.isFormTrue = true;
          } else if (newVal.indexType === "二级指标") {
            this.isFormFlase = true;
            this.isFormTrue = false;
            this.formCityList.score = "";
          }
        }
      },
      deep: true
    }
  },
  computed: {
    getDepartmentList() {
      return this.$store.state.user.departmentList;
    }
  },
  created() {
    if (this.getDepartmentList.length) {
      this.getDepartmentList.forEach(item => {
        let departmentItem = Object.assign(
          {},
          {
            value: item,
            label: item
          }
        );
        this.departmentList.push(departmentItem);
      });
    } else {
      this.departmentList.push({
        value: "暂无数据",
        label: "暂无数据"
      });
    }
    // 打开页面
    this._getCityList(this.formCityList, this.pageSize, this.pageNumber).then(
      res => {
        // res.results.firstIndex; // from表单 上级指标 seachSelect
        // res.results.firstIndex.forEach(item => {
        //   this.superiorIndexSelect.push(item.indexName);
        // });
        // this.pageTotal = parseInt(res.results.pageTotal) * 10;
        this.indexTwo = res.results.list;
        this.TableTwoLoading = false;
        // 赋值上级指标
        this.lastIndex = res.results.firstIndex;
      }
    );

    // 查询分管县领导联动下拉数据
    this._getleadersList({}).then(res => {
      console.log(res);
      if (res.code === "200") {
        var data = res.results.data;
        this.branchList = res.results.data; // 赋值
        if (data[0] !== undefined) {
          this.leaderList = data[0].userlists; // 领导数组
          this.formCityList.branchs = data[0].departAddr; // 部门
        }
      }
    });

    // 获取是否为超级管理员
    let isSuperAdmin = sessionStorage.getItem("isSuperAdmin");
    this.globalFunction2(isSuperAdmin);
  }
};
</script>
<style>
.ivu-table .demo-table-error-row td {
  background-color: #ff6600;
  color: #fff;
}
</style>
